package com.yaoz.cloud.useapiserver.rest;

import cn.hutool.json.JSONUtil;
import com.yaoz.cloud.entity.User;
import com.yaoz.cloud.serverapi.HelloRestService;
import com.yaoz.cloud.useapiserver.service.RedisService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HelloFeignRest {

    @Autowired
    private HelloRestService helloRestService;
    @Autowired
    private RedisService redisService;

    @RequestMapping(value = "/testFeign", method = RequestMethod.GET)
    public Map<String, Object> testFeign(@RequestParam("name") String name) {
        Map<String, Object> map = helloRestService.hello(name);
        return map;
    }

    @RequestMapping(value = "/copyRedisValue", method = RequestMethod.GET)
    public Map<String, Object> copyRedisValue() {
        List<User> userList = helloRestService.getAllUserInfo();
        for (User user : userList) {
            Map<String, Object> map = helloRestService.getTokenAndUserInfo(user.getUserCenterId());
            if (map == null) {
                continue;
            }
            long nowDate = new Date().getTime();
            long exitTime = (nowDate - user.getLoginDate().getTime()) / 1000;//计算出已经存在了多少秒
            String tokenValue = "\"" + StringEscapeUtils.escapeJava(JSONUtil.toJsonStr(map.get("userInfo"))) + "\"";
            String idValue = "\"" + StringEscapeUtils.escapeJava(map.get("token").toString()) + "\"";
            redisService.setStr(map.get("token").toString(), tokenValue);
            redisService.setStr("token." + user.getUserCenterId(), idValue);
            redisService.expire(map.get("token").toString(), 604800 - exitTime);
            redisService.expire("token." + user.getUserCenterId(), 604800 - exitTime);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ok", "Copy--Success");
        return map;
    }
}